package com.leetcode.leetcode1;

/**
 * @program: 寻找两个正序数组的中位数
 * @author: luhd
 * @create: 2021-08-14
 */

/**
 * 给定两个大小分别为 m 和 n 的正序（从小到大）数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数
 *
 * 示例 1：
 * 输入：nums1 = [1,3], nums2 = [2]
 * 输出：2.00000
 * 解释：合并数组 = [1,2,3] ，中位数 2
 */
public class practice04 {
    public static void main(String[] args) {
        int[] nums1 = {1,2};
        int[] nums2 = {3,4};
        Solution s = new Solution();
        s.findMedianSortedArrays(nums1,nums2);
    }
    static class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int[] result = Merge(nums1,nums2);
            int len = nums1.length+nums2.length;
            for (int i = 0; i < result.length; i++) {
                System.out.print(result[i]+" ");
            }
            //System.out.println();
            //System.out.println(result[(len+1)/2-1]);
            //System.out.println(result[(len+2)/2-1]);
            //System.out.println((result[(len+1)/2-1]+result[(len+2)/2]-1)/2);
            double a = (result[(len+1)/2-1]+result[(len+2)/2-1]);
            System.out.println(a);
            System.out.println(a/2.0);
            return a/2.0;
        }
    }
    public static int[] Merge(int[] left, int[] right){
        int len = left.length+right.length;
        int[] result = new int[len];
        for (int index=0,i=0,j=0;index<len;index++){
            if(i >= left.length){
                result[index] = right[j++];
            }else if(j >= right.length){
                result[index] = left[i++];
            }else if(left[i]>right[j]){
                result[index] = right[j++];
            }else{
                result[index] = left[i++];
            }
        }
        return result;
    }
}
